﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class TdxHelper
{
    #region  通达信窗体置顶
    // ===== Win32 API =====
    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    static extern bool IsIconic(IntPtr hWnd);   // 判断是否最小化

    // SW_RESTORE = 9
    const int SW_RESTORE = 9;

    /// <summary>
    /// 把通达信主窗口调到前台
    /// /* ===== 使用示例 =====
    ///  在按钮事件里直接调用：
    ///  TdxHelper.BringTdxToFront();
    ///  ==========================*/
    /// </summary>
    public static void BringTdxToFront()
    {
        // 1) 按窗口标题模糊查找
        Process[] ps = Process.GetProcessesByName("TdxW");   // 通达信主进程名通常是 TdxW.exe
        IntPtr hWnd = IntPtr.Zero;
        foreach (var p in ps)
        {
            if (p.MainWindowTitle.Contains("通达信"))
            {
                hWnd = p.MainWindowHandle;
                break;
            }
        }

        if (hWnd == IntPtr.Zero)
        {
            MessageBox.Show("未找到通达信窗口！");
            return;
        }

        // 2) 如果最小化，先恢复
        if (IsIconic(hWnd))
            ShowWindow(hWnd, SW_RESTORE);

        // 3) 设为前台
        SetForegroundWindow(hWnd);
    }
    #endregion

    #region 鼠标模拟
    [DllImport("user32.dll")]
    static extern bool SetCursorPos(int X, int Y);

    [DllImport("user32.dll")]
    static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

    // 鼠标事件常量
    const uint MOUSEEVENTF_LEFTDOWN = 0x02;
    const uint MOUSEEVENTF_LEFTUP = 0x04;
    const uint MOUSEEVENTF_RIGHTDOWN = 0x08;
    const uint MOUSEEVENTF_RIGHTUP = 0x10;
    /// <summary>
    /// 使用方法，SimulateLeftClick(100,100);
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    public static void SimulateLeftClick(int x, int y)
    {
        SetCursorPos(x, y); // 移动鼠标到指定位置
        mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); // 按下左键
        mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);   // 释放左键
    }

    #endregion
}

